package org.ksug.samples.springmvc;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class AccountValidator implements Validator {

	private static final String NAME = "name";
	private static final String NUMBER = "number";
	private static final String REGISTRATION_DATE = "registrationDate";

	@SuppressWarnings("unchecked")
	@Override
	public boolean supports(Class clazz) {
		return Account.class.equals(clazz);
	}

	@Override
	public void validate(Object object, Errors errors) {
		checkRequiredFields(errors);
		validateRegistrationDate(errors, ((Account) object)
				.getRegistrationDate());
	}

	private void validateRegistrationDate(Errors errors, Date registrationDate) {
		
		if (registrationDate == null)
			errors.rejectValue(REGISTRATION_DATE,
					Error.REGISTRATION_DATE_REQUIRED);
		else if (errors.hasFieldErrors(REGISTRATION_DATE)){
			errors.rejectValue(REGISTRATION_DATE,
					Error.REGISTRATION_DATE_INVALID_FORMAT);
		}else if (registrationDate.before(getStartDate())
				|| registrationDate.after(new Date()))
			errors.rejectValue(REGISTRATION_DATE,
					Error.REGISTRATION_DATE_OUT_OF_RANGE);

	}

	private Date getStartDate() {
		String startDateString = "080621";
		try {
			return new SimpleDateFormat("yyMMdd").parse(startDateString);
		} catch (ParseException e) {
			throw new IllegalStateException(startDateString + "이 적절하지 않습니다.");
		}
	}

	private void checkRequiredFields(Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, NUMBER, null,
				"번호는 반드시 입력해야 합니다.");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, NAME, null, "이름은 반드시 입력해야 합니다.");
	}

}
